<template>

    <div class="design-media">
        <UserUploader ref="uploader" />

        <UxDialog :visible="visible" @close="close()">
            <div class="media-dialog">

                <!-- 初始化加载中 -->
                <UxLoading2 class="init-loading" v-if="!inited" :loading="true" />

                <!-- 全局为空 -->
                <DesignerMediaEmpty v-else-if="empty" @doUpload="doUpload($event)" />

                <template v-else>

                    <DesignerMediaForm name="Image File" :form="form" :folders="folders" @search="getSearching($event)"
                                       @open="getDirectory($event)" @doUpload="doUpload($event)" />

                    <!-- 滚动区 -->
                    <div class="scroller" ref="scroller" @scroll="onScroll($event)" :offset="top > 1 ? 'scroll' : ''">

                        <!-- 未登录 -->
                        <div class="uploaded-list" v-if="!logined">
                            <DesignerMediaImageList :list="uploaded" @select="setSelect($event)" />
                        </div>

                        <!-- 搜索 -->
                        <div class="searching-list" v-else-if="form.name">
                            <div class="search-match">
                                <strong v-text="form.total"></strong>
                                <em v-if="form.total > 1"> matches found</em>
                                <em v-else> match found</em>
                            </div>
                            <UxSearchEmpty v-if="list.length == 0" />
                            <DesignerMediaImageList v-else :list="list" @select="setSelect($event)" />
                        </div>

                        <!-- 进入目录 -->
                        <div class="directory-list" v-else-if="form.directory">

                            <div class="directory-match" v-if="list.length > 0">
                                <strong
                                        v-text="(folders.find(i => i.id == form.directory) || {}).folder_name || ''"></strong>
                                <em v-text="directoryFiles + (directoryFiles > 1 ? ' files' : ' file')"></em>


                            </div>

                            <div class="directory-empty" v-if="list.length == 0">
                                <figure>
                                    <img src="@/assets/images/files/files-folder-nodata.png" alt="">
                                </figure>
                                <p>
                                    <strong>Folder is empty</strong>
                                    <!-- <span>Support "png,jpg,jpeg" format pictures</span> -->
                                </p>
                                <button @click="fileUpload()">Upload</button>
                            </div>
                            <DesignerMediaImageList v-else :list="list" @select="setSelect($event)" />
                        </div>

                        <!-- 外层管理 -->
                        <div class="manage-list" v-else>
                            <!-- 最近使用 -->
                            <div class="manage-list-recently" v-if="recently.length > 0">
                                <h3>Recently used</h3>
                                <DesignerMediaImageList :list="recently" @select="setSelect($event)" />
                            </div>

                            <!-- 文件夹列表 -->
                            <div class="manage-list-folders" v-if="folders.length > 0">
                                <h3>My folders</h3>
                                <DesignerMediaFolderList :list="folders" @open="getDirectory($event)" />
                            </div>

                            <!-- 图片列表 -->
                            <div class="manage-list-files" v-if="list.length > 0">
                                <h3>My files</h3>
                                <DesignerMediaImageList :list="list" @select="setSelect($event)" />
                            </div>
                        </div>

                        <div class="load-more" v-show="list.length > 0" :status="form.status">
                            <span v-if="form.status == 'loading'">-- Scroll to bottom load data --</span>
                            <span v-if="form.status == 'waiting'">-- Loading --</span>
                            <span v-if="form.status == 'nomore'"></span>
                        </div>

                    </div>

                    <UxLoading2 :loading="loading" />

                </template>

            </div>

        </UxDialog>
    </div>

</template>

<script>
import DesignResource from "@/utils/DesignResource.js";
import Md5 from "js-md5";
import { mapGetters } from "vuex";
export default {
    data () {
        return {
            inited: false,
            visible: false,
            loading: false,
            folders: [], // 文件夹列表
            recently: [], // 最近使用
            uploaded: [], // 上传中的（未登录状态下才有）
            form: { name: '', directory: 0, page: 1, size: 10, status: 'waiting', total: 0, },
            list: [], // 未归类的，搜索的，目录内的
            top: 0,
        };
    },

    computed: {
        ...mapGetters({
            logined: "getIsLogin",
        }),
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
        empty () {
            if (!this.logined) {
                // 未登录
                return this.uploaded.length == 0
            } else if (this.form.name || this.form.directory) {
                // 搜索或是路径中
                return false;
            } else {
                return this.folders.length == 0 && this.uploaded.length == 0 && this.list.length == 0 && this.recently.length == 0
            }
        },
        directoryFiles () {
            return (this.folders.find(i => i.id == this.form.directory) || {}).quantity || 0
        }
    },
    methods: {

        // 文件夹
        async getFolders () {
            const response = await this.$http("Material.getMaterialFolder");
            this.folders = response.data || [];
        },

        // 最近使用
        async getRecently () {
            const response = await this.$http("Material.getMaterialRecently");
            this.recently = response.data || [];
        },

        // 获取用户图片
        async getResourceList (option = {}) {

            const request = {
                search_name: typeof option.name != 'undefined' ? option.name : this.form.name,
                folder_id: typeof option.directory != 'undefined' ? option.directory : this.form.directory || "",
                page_num: typeof option.page != 'undefined' ? option.page : this.form.page,
                page_size: typeof option.size != 'undefined' ? option.size : this.form.size,
            };

            const response = await this.$http("Material.getUserMaterial", request);
            const list = (response.data || []).map(item => {
                item.type = '';
                item.file = null;
                item.image = null;
                item.percent = 0;
                item.error = '';
                return item;
            })


            // 清空数据
            if (request.page_num == 1) {
                this.list.splice(0, this.list.length);
                this.list = list;

            } else {
                this.list.push(...list)
            }

            this.form.total = response.total || 0;
            this.form.status = list.length < this.form.size ? "nomore" : "waiting";
        },

        // 添加最近使用
        async addRecently (image) {
            if (this.logined && image.id) {
                await this.$http("Material.setMaterialRecently/" + image.id);
                this.recently = this.recently.filter((item) => item.id != image.id);
                this.recently.unshift({ ...image });
                this.recently.splice(5, Math.max(this.recently.length - 5, 0));
            } else {
                // 未登录
            }
        },

        async bindMaterial (item) {
            const request = {
                folder_id: item.folder_id,
                file_name: item.img_name,
                file_url: item.img_url,
                file_size: item.img_size,
                width: item.width,
                height: item.height,
                img_type: item.img_type,
                preview_url: item.preview_url,
            };
            const result = await this.$http('Material.setMaterialBind', request);
            const data = result.data || {}
            item.id = data.id;
            this.addRecently(item);
            this.getResourceList({ page: 1 })
            item.folder_id && this.getFolders()

        },


        // 滚动事件
        onScroll (event) {

            const scroller = this.$refs.scroller
            if (!scroller) {
                // 没有滚动
            } else {
                this.top = scroller.scrollTop || 0;

                if (this.logined && this.form.status == "waiting") {

                    const offset = 10;
                    const inner = scroller.scrollHeight || 0
                    const outer = scroller.clientHeight || 0

                    if (inner - outer - this.top < offset) {
                        this.form.status = "loading";
                        this.form.page += 1;
                        this.getResourceList();
                    }
                }
            }
        },

        // 搜索功能
        getSearching (keywords) {
            const request = {
                name: keywords,
                page: 1,
            }
            this.loading = true;
            this.getResourceList(request).then(res => {
                this.loading = false
                this.form.name = request.name;
                this.form.page = request.page;
                this.$refs.scroller && (this.$refs.scroller.scrollTop = 0)
            });
        },

        // 进入文件夹
        getDirectory (item) {
            const request = {
                name: '',
                directory: item ? item.id : '',
                page: 1,
            }

            this.loading = true;
            this.getResourceList(request).then(res => {
                this.loading = false
                this.form.name = request.name;
                this.form.page = request.page;
                this.form.directory = request.directory;
                this.$refs.scroller && (this.$refs.scroller.scrollTop = 0)

            });
        },

        // 选中文件上传
        doUpload () {

            const email = (this.userInfo || {}).email;
            const folder = email ? Md5(email) : 'noemail';
            const option = {
                name: '',
                path: this.logined ? 'data/pod/file/' + folder : 'data/zx/design/nologin',
            }


            this.$refs.uploader && this.$refs.uploader.startUpload(option, result => {
                if (result) {
                    const item = {
                        folder_id: this.form.directory || 0,
                        id: '',
                        img_type: result.suffix,
                        img_name: result.file.name,
                        img_url: result.url,
                        img_size: result.file.size,
                        preview_url: result.thumb,
                        width: result.image.width,
                        height: result.image.height,
                        percent: 0,
                    };


                    // 缓存
                    DesignResource.setImageCache(result.url, result.image).then(result => {
                        this.setSelect(item);
                        this.$refs.uploader.close();

                        if (!this.logined) {
                            // 未登录
                            // item.id = new Date().getTime()
                            this.uploaded.unshift(item);
                        } else {
                            this.bindMaterial(item);
                        }
                    })

                } else {
                    this.$uxMessage.warning('Upload failed!');
                }
            })
        },

        // 选中图片
        setSelect (image) {
            // 已登录的，有两种情况，1.选择素材文件，2.上传文件
            let option = {
                url: image.img_url,
                name: image.img_name,
                width: image.width,
                height: image.height,
            };

            // 最近使用
            this.addRecently(image);
            // 判断id，如果有id则更新最近使用
            this.$emit("global:DESIGN_INSERT_IMAGE", option);
            this.close();
        },

        open () {
            if (!this.logined) {
                // 未登录
                this.inited = true;
                this.visible = true;
            } else {
                // 取用户数据
                this.visible = true;
                if (!this.inited) {
                    Promise.all([
                        this.getFolders(),
                        this.getRecently(),
                        this.getResourceList(),
                    ]).then((res) => {
                        this.inited = true;
                    });
                }
            }
        },
        loadAfterLogin () {

            if (this.logined && this.inited) {
                Promise.all([
                    this.getFolders(),
                    this.getRecently(),
                    this.getResourceList(),
                ])
            }
        },
        // 关闭弹窗
        close () {
            this.uploading = null;
            this.visible = false;
        },

    },

    created () {
        this.$on("global:DESIGN_OPEN_MEDIA", () => this.open());
        this.$on("global:DESIGN_MEDIA_LOGIN", () => this.loadAfterLogin());
    },
};
</script>

<style lang="scss" scoped>
.media-dialog {
    box-sizing: border-box;
    width: calc(100vw - 80px);
    height: calc(100vh - 80px);
    max-width: 1116px;
    max-height: 800px;
    display: flex;
    flex-direction: column;
    background: #f8f8f8;
    border-radius: 12px;

    &>.loading {
        border-radius: 12px;

        &.init-loading {
            background: none;
        }
    }

    .scroller {
        flex: 1;
        overflow: auto;
        position: relative;
        padding: 0 18px 0;
        border-top: 1px solid transparent;

        &[offset='scroll'] {
            border-top-color: #e6e6e6;
        }
    }

    .load-more {
        height: 50px;
        line-height: 50px;
        text-align: center;

        &[status='nomore'] {
            height: 18px;
        }
    }
}

.uploaded-list {}

.searching-list {
    min-height: 100%;
    display: flex;
    flex-direction: column;

    .search-match {
        padding: 20px 0 0;
        font-size: 18px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 18px;

        strong {
            font-weight: 500;
        }
    }

    .media-image-list {
        margin-top: 18px;
    }

    .search-empty {
        margin-top: 18px;
        margin-bottom: 18px;
        flex: 1;
    }
}

.directory-list {
    min-height: 100%;
    box-sizing: border-box;
    position: relative;

    .directory-match {
        display: flex;
        align-items: center;
        padding: 20px 0 0;

        strong {
            font-size: 16px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 18px;
        }

        em {
            margin-left: 4px;
            font-size: 14px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #087196;
            line-height: 16px;
            background: rgba(#087196, 0.05);
            border-radius: 4px;
            padding: 4px;
        }
    }

    .directory-empty {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;

        figure {
            margin-top: -10px;
        }

        img {
            width: 80px;
            height: 60px;
        }

        p {
            display: flex;
            flex-direction: column;
            text-align: center;
            margin-top: 24px;

            strong {
                font-size: 24px;
                font-family: Roboto, Roboto;
                font-weight: 500;
                color: #212121;
                line-height: 32px;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                color: #212121;
            }

            span {
                font-family: Roboto-Regular, Roboto;
                font-weight: normal;
                color: #555;
            }
        }

        button {
            margin-top: 24px;
            width: 140px;
            height: 40px;
            border-radius: 8px;
        }
    }

    .media-image-list {
        margin-top: 18px;
    }
}

.manage-list {
    h3 {
        font-size: 18px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 18px;
    }

    .media-image-list {
        margin-top: 18px;
    }

    .manage-list-folders,
    .manage-list-files {
        margin-top: 32px;
    }
}
</style>
